<?php

class service_l_favorite {

    function get_default_or_create_fav_list($user_id_or_obj) {        
        $new_list = NULL;
        if (($new_list = $this->get_default_list($user_id_or_obj)) === NULL) {
            $new_list = $this->create_list($user_id_or_obj);
        }        
        return $new_list;
    }

    public function get_default_list($user_id_or_obj){
        $id = $this->__get_id($user_id_or_obj);
        $list = new list_m_favorite();
        $list->where("user_id",$id)->where('name',module_u_favorite::DEFAULT_LIST_NAME);
        
        if($list->get()->exists()){
            return $list;
        }else{
            return NULL;
        }        
    }

    public function create_list($user_id_or_obj,$list_name=module_u_favorite::DEFAULT_LIST_NAME){
        $id = $this->__get_id($user_id_or_obj);
        $list = new list_m_favorite();
        $list->user_id = $id;
        $list->name = $list_name;
        return $list->save_as_new() ? $list : NULL;
    }

    

    public function add_item($list_id_or_obj,$product_id_or_obj){

        $list_id = $this->__get_id($list_id_or_obj);
        $product_id = $this->__get_id($product_id_or_obj);
        
        $tmp = new item_m_favorite();
        $tmp->favorite_list_id = $list_id;
        $tmp->product_id = $product_id;
        return $tmp->save();
        
    }

    public function remove_item($list_id_or_obj,$product_id_or_obj){

        $list_id = $this->__get_id($list_id_or_obj);
        $product_id = $this->__get_id($product_id_or_obj);        

        $tmp = new item_m_favorite();
        $tmp->where("favorite_list_id",$list_id);
        $tmp->where("product_id",$product_id);
        $tmp->get()->delete();        
    }

    public function remove_all_items($list_id_or_obj){
        $list_id = $this->__get_id($list_id_or_obj);
        $tmp = new item_m_favorite();
        $tmp->where("favorite_list_id",$list_id);
        return $tmp->get()->delete_all();
    }

    public function get_items($list_id_or_obj){
        $id = $this->__get_id($list_id_or_obj);
        $tmp = new item_m_favorite();
        return $tmp->where("favorite_list_id",$id)->get_iterated();
    }

    private function __get_id($obj_or_id){
        return is_object($obj_or_id) ? $obj_or_id->id : $obj_or_id;
    }
}
?>
